<template>
    <basic-container>
      <avue-crud :option="option"
                 :data="data"
                 @on-load="onLoad"
                 :page.sync="page"
                 :table-loading="loading"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange">
        <template slot="menu" slot-scope="scope">
          <el-button type="text" icon="el-icon-upload2" size="small" @click="materialUpload(scope.row)" v-if="materialIf">模板上传</el-button>
          <el-button type="text" icon="el-icon-delete" size="small" @click="materialUpdate(scope.row)" v-if="scope.row.formUrl != '' && scope.row.formUrl != null && scope.row.formUrl != undefined">清除模板</el-button>
        </template>
      </avue-crud>
      <el-dialog title="模板上传"
                 width="45%"
                 append-to-body="true"
                 :visible.sync="materialVisible">
        <avue-form v-model="materialForm" :option="materialOption" ref="materialForm" @submit="materialSave">
          <template slot-scope="scope" slot="formUrl">
            <el-upload
              class="upload-demo"
              action="/api/blade-resource/oss/endpoint/put-object"
              accept="image/jpeg,image/png,image/jpg,image/bmp,.doc,.docx,.ppt,.pptx,.txt,.xls,.xlsx,.zip"
              :before-remove="beforeRemove"
              :on-success="handleSuccess"
              :before-upload="beforeAvatarUpload"
              :file-list="fileList"
              :limit="1"
              ref="materialForm">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </template>
        </avue-form>
      </el-dialog>
    </basic-container>
</template>
<script>
    import {materialPage, materialUploadLicense, getCountMaterialLicense} from "@/api/acceptance/serviceItem";
    import {caseMaterialbeforeAvatarUpload} from "@/api/acceptance/materialfile";
    import {mapGetters} from "vuex";

    export default {
        name: "service-guide",
        components: {},
        data() {
            return {
                //材料
              option: {
                    border: true,
                    index: true,
                    indexLabel: "序号",
                    viewBtn: false,
                    simplePage: true,
                    editBtn: false,
                    addBtn: false,
                    delBtn: false,
                    refreshBtn: false,
                    align: 'center',
                    columnBtn: false,
                    column: [
                        {
                            label: "材料名称",
                            prop: "materialName",
                            width: '600px',
                            align: 'left',
                            overHidden: true
                        },
                        {
                            label: "材料类型",
                            prop: "materialType",
                            type: "select",
                            dicUrl: "/api/blade-system/dict-biz/dictionary?code=material_type",
                            props: {
                                label: "dictValue",
                                value: "dictKey"
                            },
                        },
                        {
                            label: "材料形式",
                            prop: "materialFormat",
                            type: "select",
                            dicUrl: "/api/blade-system/dict-biz/dictionary?code=material_format",
                            props: {
                                label: "dictValue",
                                value: "dictKey"
                            },
                        }, {
                            label: "材料必要性",
                            prop: "isNeed",
                            type: "select",
                            dicUrl: "/api/blade-system/dict-biz/dictionary?code=is_need",
                            props: {
                                label: "dictValue",
                                value: "dictKey"
                            },
                        }
                    ]
                },
              materialVisible: false,
              materialForm:{},
              materialOption:{
                labelWidth: 100,
                emptyBtn: false,
                submitText: '保存',
                column:[
                  {
                    label: 'rowGuid',
                    prop: 'rowGuid',
                    hide: true,
                    display: false
                  },
                  {
                    label: '材料名称',
                    prop: 'materialName',
                    disabled: true,
                    hide: true,
                    span: 24,
                    rules:[
                      {
                        required: true,
                        message: '请输入材料名称'
                      }
                    ]
                  },
                  {
                    label: '附件模板名称',
                    prop: 'formUrlName',
                    hide: true,
                    display: false
                  },
                  {
                    label: '附件模板',
                    prop: 'formUrl',
                    span: 24,
                    formslot: true,
                    rules: [
                      {
                        required: true,
                        message: '请上传附件模板'
                      }
                    ]
                  }
                ]
              },
              fileList:[],
              materialIf:false,
              materialUpdateIf:false,
              page: {
                currentPage: 1,
                pageSize: 10,
                total: 0
              },
              loading: false,
              data: [],
              query: {}
            };
        },
        computed: {
            ...mapGetters(["permission"]),
        },
        props: {
            serviceItem: {},
        },
        created(){
          getCountMaterialLicense(this.serviceItem.taskType, this.serviceItem.rowGuid).then(res => {
            if (res.data.data < 1) {
              this.materialIf = true;
            }
          })
        },
        methods: {
          materialSave(loading, done){
            this.$refs.materialForm.validate((valid) => {
              if (valid) {
                this.$confirm("确认维护该材料word模板（目前事项仅支持维护一个材料的附件模板，保存成功后，其他材料不可维护模板）", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
                }).then(() => {
                  materialUploadLicense(this.serviceItem.taskType, this.materialForm.rowGuid, this.materialForm.formUrl, this.materialForm.formUrlName, this.materialForm.taskGuid, 'update').then(res => {
                    if (res.data.data == true) {
                      this.materialVisible = false;
                      this.$message.success("操作成功")
                      this.refreshChange();
                    }else {
                      this.$message.warning("请查看后台日志")
                      this.materialVisible = false;
                      this.refreshChange();
                    }
                  })
                  this.materialIf = false;
                  done();
                }).catch(() => {
                  done();
                  loading();
                  this.materialVisible = false;
                  this.refreshChange();
                })
              }
            })
          },
          materialUpdate(row){
            this.$confirm("确认清除该材料word模板吗", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }).then(() => {
              materialUploadLicense(this.serviceItem.taskType, row.rowGuid, '1', '2', row.taskGuid, 'delete').then(res => {
                if (res.data.data == true) {
                  this.$message.success("操作成功")
                  this.materialIf = true;
                  this.refreshChange();
                }else {
                  this.$message.warning("请查看后台日志")
                  this.refreshChange();
                }
              })
            }).catch(() => {
              this.refreshChange();
            })
          },
            beforeRemove(file, reject) {
              //elementui上传组件 before-upload返回false自动调用before-remove和on-remove钩子问题解决方法
              if (file && file.status==="success") {
                return this.$confirm(`确定移除 ${ file.name }？`, {
                  confirmButtonText: '确认',
                  cancelButtonText: '取消',
                  type: 'warning',
                }).then(() => {
                  this.materialForm.formUrl = '';
                  this.materialForm.formUrlName = '';
                  this.$message({
                    type: 'success',
                    message: '删除成功!'
                  });
                }).catch(() => {
                  this.$message({
                    type: 'info',
                    message: '已取消删除!'
                  });
                  reject(false);
                })
              }
            },
            handleSuccess(res){
              if(res.code == 200 ){
                this.$message.success("上传成功");
                this.materialForm.formUrl = res.data.link;
                this.materialForm.formUrlName = res.data.originalName;
              }else{
                this.$message.warning(res.msg);
              }
            },
            beforeAvatarUpload(file) {
              if(file.size == 0) {
                this.$message({
                  type: "error",
                  message: "不允许上传空文件"
                });
                return false;
              }else{
                return caseMaterialbeforeAvatarUpload(file,this);
              }
            },
            materialUpload(row){
              if (row.formUrl != null && row.formUrl != '' && row.formUrl != undefined) {
                this.fileList = [];
                let file = {};
                let name = row.formUrlName;
                let url = row.formUrl;
                file = {name, url};
                this.fileList.push(file);
                this.materialForm.formUrl = row.formUrl;
                this.materialForm.formUrlName = row.formUrlName;
              }else {
                this.fileList = [];
              }
              this.materialForm.rowGuid = row.rowGuid;
              this.materialForm.taskGuid = row.taskGuid;
              this.materialForm.materialName = row.materialName;
              this.materialVisible = true;
            },
            onLoad(page, params = {}) {
                this.loading = true;
                params.taskCode = this.serviceItem.taskCode;
                params.taskType = this.serviceItem.taskType;
                params.taskGuid = this.serviceItem.rowGuid;
                materialPage(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
                    const data = res.data.data;
                    this.page.total = data.total;
                    this.data = data.records;
                    this.loading = false;
                });
            },
            searchReset() {
                this.query = {};
                this.onLoad(this.page);
            },
            searchChange(params, done) {
                this.query = params;
                this.page.currentPage = 1;
                this.onLoad(this.page, params);
                done();
            },
            currentChange(currentPage) {
                this.page.currentPage = currentPage;
            },
            sizeChange(pageSize) {
                this.page.pageSize = pageSize;
            },
            refreshChange() {
                this.onLoad(this.page, this.query);
            }
        },
        watch: {}
    };
</script>
<style scoped lang="scss">
    /deep/.avue-crud__menu {
        min-height: 0px;
    }
    ///deep/.el-input.is-disabled .el-input__inner {
    //    background-color: #FFF;
    //    color: #606266;
    //}
    ///deep/.el-textarea.is-disabled .el-textarea__inner {
    //    background-color: #FFF;
    //    color: #606266;
    //}
</style>
